package org.csu.web.servlets;

import org.csu.domain.Account;
import org.csu.domain.Cart;
import org.csu.service.CartService;
import org.csu.service.CategortService;
import org.csu.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class ViewCartServlet extends HttpServlet {
    private String username=null;
    private int cartListsize=0;
    private BigDecimal subtoatl;
    private static final String VIEW_CART="/WEB-INF/jsp/cart/Cart.jsp";
    private static final String VIEW_LOGIN="/WEB-INF/jsp/account/SignonForm.jsp";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Cart cart = (Cart)session.getAttribute("cart");

        Account account = (Account)session.getAttribute("account");
        username=req.getParameter("username");
        CartService cartService = new CartService();
        List<Cart> cartList = new ArrayList<Cart>();
        if(username != ""){
            HttpServletRequest httpRequest= req;
            String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());
            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + strBackUrl + " 查看购物车 " + cart;
            logService.insertLogInfo(username, logInfo);
            cartList = cartService.getCartByusername(username);
            cartListsize = cartList.size();
            if(cart==null){
                cart=new Cart();
            }
            session.setAttribute("cart",cart);
            subtoatl=new BigDecimal(0);
            int i=0;
            while (i<cartListsize){
                subtoatl=subtoatl.add(cartList.get(i).getTotal());
                i++;
            }
            session.setAttribute("cartList",cartList);
            session.setAttribute("cartListsize",cartListsize);
            session.setAttribute("subTotal",subtoatl);
            req.getRequestDispatcher(VIEW_CART).forward(req,resp);
        }else if (username==""){
            req.getRequestDispatcher(VIEW_LOGIN).forward(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
